//引入express模块
const express = require('express')
//创建路由器对象
const router = express.Router()
//引入连接池模块
const pool = require('../pool.js')
module.exports = router


//管理员登录
router.post('/login', (req, res) => {
	var obj = req.body
	console.log(obj)
	pool.query('select * from admin_user where account=? && password=?', [obj.account, obj.password], (err, r) => {
		if (err) {
			throw err
		}
		console.log(r)
		if (r.length == 0) {
			res.send({ code: 400, msg: '登录失败' })
		} else {
			res.send({ code: 200, msg: '登陆成功' })
		}
	})
})
// 获取全部管理员信息
router.get('/admin_detail', (req, res) => {
	pool.query('select * from admin_user', (err, r) => {
		if (err) {
			throw err
		}
		console.log(r)
		if (r.length == 0) {
			res.send({ code: 400, msg: '查询失败', data: r })
		} else {
			res.send({ code: 200, msg: '查询成功', data: r })
		}
	})
})

// 修改管理员信息
router.put('/admin_change', (req, res, next) => {
	//获取put传递的参数
	var obj = req.body
	console.log(obj)
	pool.query('update admin_user set ? where id=?', [obj, obj.id], (err, r) => {
		if (err) {
			return next(err)
		}
		console.log(r)
		if (r.changedRows == 1) {
			res.send({ code: 200, msg: '修改成功' })
		} else {
			res.send({ code: 400, msg: '修改失败' })
		}
	})
})

// 删除管理员
router.delete('/:id', (req, res, next) => {
	pool.query('delete from admin_user where id=?', [req.params.id], (err, r) => {
		if (err) {
			return next(err)
		}
		console.log(r)
		if (r.affectedRows == 0) {
			res.send({ code: 400, msg: '删除失败' })
		} else {
			res.send({ code: 200, msg: '删除成功' })
		}
	})
})

// 后台添加管理员
router.post('/register', (req, res, next) => {
	let account = req.body.account
	let password = req.body.password
	var obj = req.body


	let sql = 'select count(account) as count from admin_user where account=?'

	pool.query(sql, account, (err, r) => {
		if (err) {
			throw err
		}
		let count = r[0].count
		if (count == 0) {
			let sql = 'insert into admin_user set?'
			pool.query(sql, [obj], (err, r) => {
				if (err) {
					throw err
				}
				res.send({ code: 200, msg: '注册成功' })
			})
		} else {
			res.send({ code: 401, msg: '注册失败,用户名已经存在' })
		}
	})
})